package com.hitsz.application;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.hitsz.R;

import org.json.JSONArray;

import java.io.IOException;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class RegisterActivity extends AppCompatActivity
        implements View.OnClickListener{
    private OkHttpClient okHttpClient = new OkHttpClient();
    private String TAG = "cat";
    private String res;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        res = "";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        findViewById(R.id.register_button2).setOnClickListener(this);
    }

    // 返回后只能回到主界面
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
            startActivity(intent);
            this.finish();
        }
        return true;
    }


    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.register_button2){

            // 获取文本框对象
            EditText etUsername = (EditText)findViewById(R.id.register_username_editText);
            EditText etPassword = (EditText)findViewById(R.id.register_password_editText);
            EditText etPasswordConfirm = (EditText)findViewById(R.id.confirm_password_editText);
            EditText etRgCode = (EditText)findViewById(R.id.register_code_editText);

            // 获取文本框内容
            String username = etUsername.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            String passwordConfirm = etPasswordConfirm.getText().toString().trim();
            String rgCode = etRgCode.getText().toString().trim();

            // 用户名和密码不为空 且 两次输入密码相等 且 注册码正确
            if( !userNameMatch(username)){
                // 用户名格式错误
                Toast toast=Toast.makeText(this, "用户名应为5-15位,以字母开头且只包含字母 数字 _ -",Toast.LENGTH_SHORT);
                toast.show();
            }
            else if( !passwordMatch(password) ){
                // 密码格式错误
                Toast toast=Toast.makeText(this, "密码应为5-20位,只包含字母 数字 _-,./@#",Toast.LENGTH_SHORT);
                toast.show();
            }
            else if(!password.equals(passwordConfirm)){
                //两次输入密码不相等
                Toast toast=Toast.makeText(this, "两次密码输入不一致！\n请重新输入！",Toast.LENGTH_SHORT);
                toast.show();
            }else if(!rgCode.equals("cat")){
                // 注册码不正确
                Toast toast=Toast.makeText(this, "注册码无效！",Toast.LENGTH_SHORT);
                toast.show();
            }else{
                // 注册成功
                postSend(username,password);

                // 睡三秒钟等待响应
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if(res != null){
                    if(res.equals("{\"status\":0,\"message\":\"注册成功！\"}")){
                        Toast toast=Toast.makeText(this, "注册成功，请完成登陆！",Toast.LENGTH_SHORT);
                        toast.show();
                        // 跳转到登陆界面
                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                        startActivity(intent);
                        this.finish();
                    }
                    else if(res.equals("")){
                        Toast toast=Toast.makeText(this, "注册超时!",Toast.LENGTH_SHORT);
                        toast.show();
                    }
                    else{
                        Toast toast=Toast.makeText(this, "用户名已被占用！",Toast.LENGTH_SHORT);
                        toast.show();
                    }
                }
            }
        }
    }

    public void postSend(String username, String password){
        new Thread(){
            @Override
            public void run(){
                FormBody formBody = new FormBody.Builder()
                        .add("username",username)
                        .add("password",password).build();
                Request request = new Request.Builder()
                        .url("http://192.168.56.1:3007/api/reguser")
                        .post(formBody).build();
                Call call = okHttpClient.newCall(request);

                try {
                    Response response = call.execute();
                    res = response.body().string();
                    Log.i(TAG,"getSync:"+res);
                } catch (IOException e) {
                    System.out.println("cat");
                    e.printStackTrace();
                }

            }
        }.start();
    }

    // 用于匹配用户名是否符合规范 5-15位 以字母开头且只包含字母 数字 _ -
    private boolean userNameMatch(String userName){
        String pattern = "^[a-zA-Z][a-zA-Z0-9_-]{4,14}$";
        return (Pattern.matches(pattern, userName));
    }

    // 用于匹配密码是否符合规范 5-20位 只包含字母 数字 - _ , . / @ #
    private boolean passwordMatch(String password){
        String pattern = "^[a-zA-Z0-9_,./@#-]{5,20}$";
        return (Pattern.matches(pattern, password));
    }


}